package com.mlz.mlzmall.ui.activity.act.personal.userLogin;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Response;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.bean.UserBean;
import com.mlz.mlzmall.ui.activity.act.base.TopTitleView;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.MyCenterUtils;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.RequestUtils;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.VolleyBaseActivity;
import com.mlz.mlzmall.ui.utils.util.ACache;
import com.mlz.mlzmall.ui.utils.vali.AbStrUtil;
import com.mlz.mlzmall.ui.utils.vali.UIUtils;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @description 忘记密码
 * Created by 安帅 on 2016/5/24 19:44.
 */
public class ForgetPasswordActivity extends VolleyBaseActivity implements View.OnClickListener {
    private static final String TGA = "ForgetPasswordActivity";
    private UserBean userBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.forget_password_activity);
        userBean = new UserBean();
        assignViews();
        setViewContent();
        setViewClickLinstener();
        getSession();
    }

    private TopTitleView forgetTopTitle;
    private EditText etForgetpasswordPhonenumber;
    private TextView tvCode;
    private EditText etCode;
    private TextView tvGetCode;
    private Button btnForgetpasswordAndCode;

    private void assignViews() {
        forgetTopTitle = (TopTitleView) findViewById(R.id.forget_top_title);
        etForgetpasswordPhonenumber = (EditText) findViewById(R.id.et_forgetpassword_phonenumber);
        tvCode = (TextView) findViewById(R.id.tv_code);
        etCode = (EditText) findViewById(R.id.et_code);
        tvGetCode = (TextView) findViewById(R.id.tv_get_code);
        btnForgetpasswordAndCode = (Button) findViewById(R.id.btn_forgetpassword_and_code);
    }

    private void setViewContent() {
        forgetTopTitle.setLeftButtonContent(null, R.mipmap.pic_2_1_btn_back, null);
        forgetTopTitle.setTitleButtonContent("忘记密码", null, null);
    }

    private void setViewClickLinstener() {
        tvGetCode.setOnClickListener(this);
        btnForgetpasswordAndCode.setOnClickListener(this);
        forgetTopTitle.setOnLeftButtonClickListener(new TopTitleView.OnLeftButtonClickListener() {
            @Override
            public void onLeftBtnClick(View button) {
                finish();
                ForgetPasswordActivity.this.overridePendingTransition(R.anim.right_in, R.anim.right_out);
            }
        });

    }

    CountDownTimer messageTimer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            if (tvGetCode != null) {
                tvGetCode.setText("重新发送（" + (int) (millisUntilFinished / 1000) + "）");
            }
        }

        @Override
        public void onFinish() {
            if (tvGetCode != null) {
                tvGetCode.setText("重新获取验证码");
            }
        }
    };
    private String loginName, code;
    private String type = "findPassword";

    /**
     * 获取验证码
     */
    private void getMessageCode() {
        loginName = etForgetpasswordPhonenumber.getText().toString().trim();
        userBean.setAccout(loginName);
        Log.i("手机号", loginName);
        if (!AbStrUtil.isMobileNO(loginName)) {
            MyCenterUtils.ToastText("手机格式有误");
            return;
        }
        if (UIUtils.canSendMessage()) {
            UIUtils.saveTimeSendMessage();
            messageTimer.start();
            executeRequest(RequestUtils.getMLZRequestCode(mContext, loginName, type, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    try {
                        JSONObject json = new JSONObject(jsonObject.toString());
                        String msg = json.getString("msg");
                        MyCenterUtils.ToastText(msg);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }));

        } else {
            MyCenterUtils.ToastText("短信请求已发送，请耐心等待");
        }
    }
    private void getSession() {
        executeRequest(RequestUtils.getSession(mContext, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject json = new JSONObject(s);
                    String data = json.getString("data");
                    JSONObject json1 = new JSONObject(data);
                    String sessionKey = json1.getString("sessionKey");
                    // 把 sessionKey 字符串保存到手机内部存储卡
                    ACache mCache = ACache.get(getApplication());
                    Log.i(TGA, "注册获取的session:" + data);
                    // 存放时间设定为1天,默认数量为1，更新会覆盖前面的值
                    if (data != null) {
                        mCache.put("sessionKeyTest", sessionKey, ACache.TIME_DAY);
                        Log.i(TGA, "取出session：" + ACache.get(getApplication()).getAsString("sessionKeyTest"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }));
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_get_code:
                getMessageCode();
                break;
            case R.id.btn_forgetpassword_and_code:
                loginName = etForgetpasswordPhonenumber.getText().toString().trim();
                code = etCode.getText().toString().trim();
                if (loginName.length() == 0 || code.length() == 0) {
                    MyCenterUtils.ToastText("手机号或验证码不能为空");
                    return;
                }
                executeRequest(RequestUtils.getMLZForgetPwd(mContext,loginName, code, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Log.i(TGA, "返回的数据" + jsonObject.toString());
                        try {
                            JSONObject json = new JSONObject(jsonObject.toString());
                            int status = json.getInt("status");
                            if (0 == status) {
                                Intent intent = new Intent(ForgetPasswordActivity.this, ChangePasswordAgain.class);
                                enterActivityWithFinish(intent);
                            }
                            if (0 != status) {
                                String msg = json.getString("msg");
                                MyCenterUtils.ToastText(msg);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                }));
                break;
        }
    }
}
